package com.yicong.ants.manager;


import static com.zx.sdk.util.LogHelper.KEY_ADV_LOGS;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.view.View;
import android.view.Window;

import com.blankj.utilcode.util.AppUtils;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.DevHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.interfaces.BaseStateView;
import com.cchao.simplelib.util.CallBacks;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UuidUtil;
import com.danikula.vcache.HttpProxyCacheServer;
import com.google.gson.JsonParser;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.smtt.sdk.WebStorage;
import com.tencent.smtt.sdk.WebView;
import com.umeng.cconfig.UMRemoteConfig;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.base.ListRespBean;
import com.yicong.ants.bean.find.CateBean;
import com.yicong.ants.bean.home.ChannelBean;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.ui.other.FragmentContainerActivity;
import com.zx.sdk.util.LogHelper;
import com.zx.sdk.util.SPHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;


/**
 * @author cchao
 * @version 2019-05-05.
 */
public class AppHelper {

    static List<CateBean> mCateBeans = new ArrayList<>();
    public static ListRespBean<ChannelBean> mChannels;
    public static int testEnvVisible;
    public static int mCurMainTabIndex;
    public static int mShortVideoTimes = -1; // 短视频剩余观看次数（=0时会请求获取活跃度）
    public static boolean mIsMarketPkg = false;
    public static HttpProxyCacheServer mProxy;
    public static JsonParser mParser = new JsonParser();

    public static boolean isDebug() {
        return BuildConfig.Ant_Debug;
    }

    public static List<CateBean> getCateBeans() {
        return mCateBeans;
    }

    public static void turnToAppointAty(Context mContext) {
        Router.turnTo(mContext, FragmentContainerActivity.class)
                .putExtra(Constants.Extra.Fragment, Constants.Container.AppointHistory)
                .putExtra(Constants.Extra.Title, "预约记录")
                .start();
//        }
    }

    public static void setCateBeans(List<CateBean> cateBeans) {
        mCateBeans = cateBeans;
    }

    public static void getNewsChannels(BaseStateView stateView, CallBacks.Object<ListRespBean<ChannelBean>> callBack) {
        if (mChannels != null) {
            if (callBack != null) {
                callBack.onCallBack(mChannels);
            }
            return;
        }
        Disposable subscribe = RetrofitHelper.getApis().homechannel()
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    mChannels = respBean;
                    if (callBack != null) {
                        callBack.onCallBack(respBean);
                    }
                }, RxHelper.getSwitchErrorConsumer(stateView));
    }

    public static void showDevDialog2(Activity context) {
        List<DevHelper.DevOptionItem> list = new ArrayList<>();
        list.add(DevHelper.DevOptionItem.get()
                .setName("【开启广告日志】")
                .setCallBack(str -> {
                    try {
                        SPHelper.put(KEY_ADV_LOGS, true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (Settings.canDrawOverlays(context)) {
                                LogHelper.showLogs();
                            } else {
                                context.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }));
        list.add(DevHelper.DevOptionItem.get()
                .setName("【关闭广告日志】")
                .setCallBack(str -> {
                    try {
                        SPHelper.put(KEY_ADV_LOGS, false);
                        RxHelper.timerConsumer(1000, aLong -> AppUtils.relaunchApp(true));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }));
        list.add(DevHelper.DevOptionItem.get()
                .setName("【测试环境】")
                .setCallBack(str -> {
                    PrefHelper.putString(Constants.Prefs.Dev_Api, "http://" + BuildConfig.Dev_Ip);
                    RxHelper.timerConsumer(1000, aLong -> AppUtils.relaunchApp(true));
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("【正式环境】")
                .setCallBack(str -> {
                    PrefHelper.putString(Constants.Prefs.Dev_Api, Constants.Api_Product);
                    RxHelper.timerConsumer(1000, aLong -> AppUtils.relaunchApp(true));
                }));

        if (AppHelper.isDebug()) {
            list.add(DevHelper.DevOptionItem.get()
                    .setName("token")
                    .setNeedInput(true)
                    .setCallBack(str -> {
                        if (UserManager.getUserBean() == null) {
                            UserManager.updateUserBean(new UserBean());
                            UserManager.getUserBean().setId("23423");
                            UserManager.getUserBean().setMobile("15898765432");
                        }
                        UserManager.getUserBean().setJwt_token(str);
                        UserManager.refreshUserInfo();
                    }));
        }

        list.add(DevHelper.DevOptionItem.get()
                .setName("oaid")
                .setCallBack(str -> {
                    UiHelper.showConfirmDialog(context, UuidUtil.getUniqueID(context), null);
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("临时功能")
                .setCallBack(str -> {
                    RxBus.get().postEvent(Constants.Event.Bio_Auth, "x");
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("临时功能2")
                .setCallBack(str -> {
                    RxHelper.timerConsumer(1000, aLong -> {
                        //
                    });
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("清空sp")
                .setCallBack(str -> {
                    PrefHelper.clear();
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("清空浏览器缓存")
                .setCallBack(str -> {
                    LibCore.getContext().deleteDatabase("webview.db");
                    LibCore.getContext().deleteDatabase("webviewCache.db");
                    new WebView(LibCore.getContext()).clearCache(true);
                    WebStorage.getInstance().deleteAllData();
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("打开 web 页")
                .setNeedInput(true)
                .setCallBack(str -> {
                    Router.turnTo(context, YcWebViewActivity.class)
                            .putExtra(Const.Extra.Web_View_Url, str)
                            .putExtra(Const.Extra.Web_View_Tile, str)
                            .start();
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("本地测试服ip")
                .setNeedInput(true)
                .setCallBack(str -> {
                    if (str.startsWith("http")) {
                        PrefHelper.putString(Constants.Prefs.Dev_Api, str);
                    } else {
                        PrefHelper.putString(Constants.Prefs.Dev_Api, "http://" + str);
                    }
                    RxHelper.timerConsumer(600, aLong -> System.exit(0));
                    restartApp(context);
                }));

        list.add(DevHelper.DevOptionItem.get()
                .setName("ad manager")
                .setNeedInput(true)
                .setCallBack(str -> {
                    Activity activity = context;
                    Logs.d("ad manager " + str + " 1 ");


                }));

        DevHelper.showDevOptionDialog(context, "4567", list);
    }

    public static boolean isTestEnv() {
        String api = PrefHelper.getString(Constants.Prefs.Dev_Api, Constants.Api_Product);
        return !api.equals(Constants.Api_Product);
    }

    public static int getTestEnvVisible() {
        return isTestEnv() ? View.VISIBLE : View.GONE;
    }

    public static void showDevItems(Context context) {
        Map<String, String> map = new HashMap<>(8);
        map.put("0", Constants.Api_Product);
        map.put("1", "https://api.yctourism.com");
        map.put("2", "http://127.0.0.1");

        // 开发者选项
        UiHelper.showItemsDialog(context, "开发者选项", new String[]{"手机台api", "api.yctourism.com", "本地环境127"}
                , (dialog2, which) -> {
                    switch (which) {
                        case 0:
                        case 1:
                        case 2:
                            PrefHelper.putString(Constants.Prefs.Dev_Api, map.get(String.valueOf(which)));
                            RxHelper.timerConsumer(600, aLong -> System.exit(0));
                            restartApp(context);
                            break;
                    }
                });
    }

    static void restartApp(Context context) {
        Intent intent = context.getApplicationContext().getPackageManager()
                .getLaunchIntentForPackage(context.getApplicationContext().getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1500, restartIntent);
    }

    public static HttpProxyCacheServer getProxy() {
        if (mProxy == null) {
            mProxy = new HttpProxyCacheServer(LibCore.getContext());
        }
        return mProxy;
    }

    public static void transStatus(Window window) {
        // 透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.setStatusBarColor(UiHelper.getColor(R.color.transparent));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    public static String getUploadPath(LocalMedia media) {
        if (media.getMimeType().contains("video")) {
            return media.getRealPath();
        } else if (media.getMimeType().contains("image")) {
            if (media.isCompressed()) {
                return media.getCompressPath();
            }
            return media.getRealPath();
        }
        return media.getCutPath();
    }

    public static String getUmConfig(String config, String defaultValue) {
        String value = UMRemoteConfig.getInstance().getConfigValue(config);
        if (StringHelper.isEmpty(value)) {
            return defaultValue;
        }
        return value;
    }

    public static String x() {
        return "_3K";
    }

    public static String getCurrentProcessName(Context context) {
        int pid = Process.myPid();
        String currentProcessName = "";
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
            if (pid == processInfo.pid) {
                currentProcessName = processInfo.processName;
            }
        }
        return currentProcessName;
    }

    public static String getAppVersionCode() {
        return String.valueOf(BuildConfig.VERSION_CODE);
    }

    public static void tryRun(Runnable runnable) {
        try {
            runnable.run();
        } catch (Exception exception) {
            Logs.logException(exception);
        }
    }
}
